package com.发布订阅模式;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/8/9 13:57
 * @description:
 * @version:
 */
//消息代理
public class MessageBroker {
    private Map<String, List<Subscriber>> topics = new HashMap<>();

    public void publish(String topic, String message) {
        List<Subscriber> subscribers = topics.get(topic);
        if (subscribers != null) {
            for (Subscriber subscriber : subscribers) {
                subscriber.receive(message);
            }
        }
    }

    public void subscribe(String topic, Subscriber subscriber) {
        List<Subscriber> subscribers = topics.get(topic);
        if (subscribers == null) {
            subscribers = new ArrayList<>();
            topics.put(topic, subscribers);
        }
        subscribers.add(subscriber);
    }

    public void unsubscribe(String topic, Subscriber subscriber) {
        List<Subscriber> subscribers = topics.get(topic);
        if (subscribers != null) {
            subscribers.remove(subscriber);
            if (subscribers.isEmpty()) {
                topics.remove(topic);
            }
        }
    }
}
